package top.lingchen.blogadmin.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import top.lingchen.blogadmin.bean.Admin;
import top.lingchen.blogadmin.bean.Permission;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author 凌宸
 * @create 2021-12-20 下午 2:40
 * @Description
 * @Version 1.0
 */
@Service
public class AuthService {
    @Autowired
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication){
        // 获取请求路径
        String requestURI = request.getRequestURI();
        Object principal = authentication.getPrincipal();
        if(principal == null || "anonymousUser".equals(principal)){
            // 未登录
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUsername(username);
        if(admin == null){
            return false;
        }
        Long adminId = admin.getId();
        if(adminId == 1){
            // 超级管理员，直接放行
            return true;
        }
        List<Permission> permissionList = adminService.findPermissionByAdminId(adminId);
        requestURI = StringUtils.split(requestURI, '?')[0];
        for (Permission permission : permissionList){
            if(requestURI.equals(permission.getPath())){
                return true;
            }
        }
        return false;
    }

}
